package org.NooLab.somclients.comm;

import java.util.Observable;
import java.util.Observer;


import org.NooLab.itexx.comm.tcp.box.TcpBox;
import org.NooLab.somclients.*;
import org.NooLab.somclients.components.SomClients;
import org.NooLab.somclients.components.SomClientsProperties;
import org.NooLab.utilities.logging.PrintLog;


/**
 * 
 * 
 * 
 *
 */
public class TcpAdmin {

	SomClients somClients;
	SomClientsProperties somClientsProperties ;
	
	ServiceBox serviceBox ;
	ClientBox clientBox ;
	
	PrintLog out;
	// ========================================================================
	public TcpAdmin(SomClients scs, SomClientsProperties scsProps){
		
		somClients = scs;
		somClientsProperties = scsProps ;
		
		out = scs.getOut() ;
	}
	// ========================================================================
	
	/**
	 *  that's only for stuff concerning the SomClients host itself
	 * @throws Exception 
	 */
	public void createTcpServiceBox() throws Exception{
		
		serviceBox = new ServiceBox() ;
		TcpBox tcp = new TcpBox();
		
		int[] srvPorts = somClientsProperties.getServicePorts();
		
		/*
		 		-serviceports: in7202, out7201
				-systemports: in7212, out7211 
		 */
		// "client" for the other "server"
		//              clientport, ctrlport  
		// tcp.createSender( -1, srvPorts[1], "sender in somClient Service Box") ;
		// actually, we do not create the senders right now, as we send either in blackboard mode
		// or to dedicated comm-partners; the address of those we know from registration
		
		// "server" for the other "client"
		tcp.createReceiver(  srvPorts[0], srvPorts[1], serviceBox , "receiver in somClients Service Box");
				 			// listenport, ctrlport for responses
							//  in7202,    out7201 
	}

	/**
	 *  that's only for stuff concerning the communication to and from the clients
	 * @throws Exception 
	 */
	public void createTcpClientsBox() throws Exception{

		clientBox = new ClientBox() ;
		
		TcpBox tcp = new TcpBox();
		
		int[] sysPorts = somClientsProperties.getSystemPorts();

		// "server" for the other "client"
		tcp.createReceiver(  sysPorts[0], sysPorts[1], clientBox , "receiver in somClients Client Box");
				 			// listenport, ctrlport for responses
							// in7212,     out7211  

	}

	class ClientBox implements Observer{

		
		@Override
		public void update(Observable senderObj, Object msgObj) {
			// 
			
			out.print(2, "message received through TCP for ClientBox");
			// fork into an interpreting object, ...this will then call routines in "SomClients"
			(new ClientBoxMessageInterpreter( somClients, senderObj)).go() ;
		}
		
	}
	
	class ServiceBox implements Observer{

		@Override
		public void update(Observable senderObj, Object msgObj) {
			// 
			 
			out.print(2, "message received through TCP for ServiceBox");
			(new ServiceBoxMessageInterpreter( somClients, senderObj)).go() ;
		}
		
	}
	
	
	
}
